<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class ResetPasswordController extends Controller
{
    protected $redirectTo = '/';

    public function __construct()
    {
        $this->middleware('guest');
    }

    public function showResetPwdForm()
    {
        return view('home.auth.reset_pwd');
    }

    public function reset(Request $request)
    {
        $this->validator($request->all())->validate();

        $mobile = $request->input('mobile');
        $password = $request->input('password');
        $event = $request->input('event');
        $captcha = $request->input('captcha');
        $event_captcha = Session::pull($event . $mobile);
        if ($event_captcha != $captcha) {
            return redirect('/')->with(['error' => '验证码错误']);
        }
        $user = User::where('mobile', $mobile)->first();

        $user->update([
            'password' => Hash::make($password)
        ]);
        return $this->resetted($request, $user) ?: redirect($this->redirectTo)->with('success', '重置密码成功');
    }


    protected function resetted(Request $request, $user)
    {
        // 重置密码日志
        OperateLog::create([
            'username' => $user->name,
            'operate' => '重置密码成功',
            'ip' => $request->ip(),
            'method' => $request->method(),
            'UserAgent' => $request->userAgent(),
            'data' => json_encode($request->input())
        ]);
    }

    protected function guard()
    {
        return Auth::guard();
    }

    protected function validator(array $data)
    {
        $messages = [
            "mobile.required" => '用户名不能为空',
            'password.required' => '密码不能为空',
            'captcha.required' => '验证码不能为空',
            'mobile.regex' => '手机号码格式错误',
            'password.min' => '密码最短为6个字符',
            'password.confirmed' => '密码两次输入不一致',
            'verify_code.captcha' => '验证码错误',
        ];

        return Validator::make($data, [
            'mobile' => ['required', 'regex:/^1[345789][0-9]{9}$/'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'captcha' => ['required'],
            'verify_code' => ['required', 'captcha'],
        ], $messages);
    }
}
